<script lang="jsx" setup>
import XEUtils from 'xe-utils'

// 插槽处理
let slots = computed(() => Object.keys(useSlots()))
// 搜索表单处理
const attrs = XEUtils.clone(XEUtils.merge({}, useAttrs()), true)
const data = attrs.formConfig || {}
const defaultValue = Object.assign({}, data)
const getSourceValue = () => XEUtils.clone(defaultValue, true)
const form = ref(getSourceValue())
// 设置表单方法
const getForm = () => form.value
// 设置表单方法
const setForm = (val) => {
  form.value = Object.assign({}, getSourceValue(), val)
}
// 设置表单字段方法
const setFormField = (field, val) => {
  form.value[field] = val
}
// 重置表单方法
const resetForm = () => {
  form.value = getSourceValue()
}

const getQueryForm = () => {
  const searchForm = {}
  const noNull = (val) => val || val === 0 // 非空值
  for (const key in form.value) {
    if (!key) continue
    const val = form.value[key];
    if (XEUtils.isObject(val) && val !== null) { // 值为对象
      const keys = Object.keys(val)
      const { range, value } = val
      if (keys.includes('type')) { // 有type的特殊对象
        const { type, start, end } = val
        if (!noNull(type)) continue
        // 处理结构为 { type: '', value: '' } 的对象
        if (keys.includes('value')) {
          // range代表值需要拆分成 { start, end }
          if (range && Array.isArray(value)) {
            const [s, e] = value || [undefined, undefined]
            if (noNull(s) || noNull(e)) {
              searchForm[type] = { start: s, end: e }
            }
          } else {
            if (noNull(value)) {
              searchForm[type] = value
            }
          }
        }
        // 处理结构为 { type: '', start: '', end: '' } 的对象
        if (keys.includes('start') && keys.includes('end')) {
          (noNull(start) || noNull(end)) && (searchForm[type] = { start, end })
        }
      } else { // 没有type的普通对象
        if (range && Array.isArray(value)) {
          // range代表值需要拆分成 { start_key, end_key }
          const [startKey, endKey] = val.rangeKeys // 自定义key
          const [s, e] = value || [undefined, undefined]
          noNull(s) && (searchForm[startKey || 'start_' + key] = s)
          noNull(e) && (searchForm[endKey || 'end_' + key] = e)
        } else {
          if (noNull(val)) {
            searchForm[key] = val
          }
        }
      }
    } else { // 值为非对象
      if (noNull(val)) {
        searchForm[key] = val
      }
    }
  }
  return searchForm
}

const gridRef = ref()


// 暴露属性及方法
defineExpose({ getForm, setForm, setFormField, getQueryForm, resetForm })
</script>

<template>
  <div class="">
    <div v-if="slots.includes('form')">
      <div class="">
        <slot name="form" v-bind="{ form }" />
      </div>
    </div>
  </div>
</template>

<style lang="scss"></style>